import os
from unittest.mock import patch

import pytest
import pytest_asyncio
from httpx import AsyncClient
from pytest_asyncio import is_async_test

from tree_rag.app import app
from tree_rag.es import clear_all
from tree_rag.utils.parse_data_from_excel import prapare_data_from_excel

TEST_FOLDER = os.path.dirname(os.path.abspath(__file__))

ASSETS_DIR = os.path.join(TEST_FOLDER, "assets")

TEST_DATASET_ID = "test_dataset_id"
TEST_TENANT_ID = "test_tenant_id"
TEST_CHANNEL_ID = "test_channel_id"


def pytest_collection_modifyitems(items):
    pytest_asyncio_tests = (item for item in items if is_async_test(item))
    session_scope_marker = pytest.mark.asyncio(loop_scope="session")
    for async_test in pytest_asyncio_tests:
        async_test.add_marker(session_scope_marker, append=False)


def pytest_addoption(parser):
    parser.addoption(
        "--init", action="store_true", default=False, help="init test data"
    )
    parser.addoption(
        "--delete", action="store_true", default=False, help="delete test data"
    )


@pytest.fixture(autouse=True, scope="session")
def index_name_mock():
    from tree_rag import CLARIFY_INDEX, DATASET_INDEX, EXPLANATION_INDEX

    with (
        patch("tree_rag.DATASET_INDEX", f"test_{DATASET_INDEX}"),
        patch("tree_rag.EXPLANATION_INDEX", f"test_{EXPLANATION_INDEX}"),
        patch("tree_rag.CLARIFY_INDEX", f"test_{CLARIFY_INDEX}"),
    ):
        yield


@pytest.fixture(scope="session")
def dataset_id():
    return TEST_DATASET_ID


@pytest.fixture(scope="session")
def tenant_id():
    return TEST_TENANT_ID


@pytest.fixture(scope="session")
def channel_id():
    return TEST_CHANNEL_ID


@pytest_asyncio.fixture(loop_scope="session", autouse=True, scope="session")
async def prepare_data(request):
    if request.config.getoption("--init"):
        test_data_file = os.path.join(ASSETS_DIR, "test_qa.xlsx")
        await prapare_data_from_excel(
            test_data_file, TEST_DATASET_ID, TEST_TENANT_ID, TEST_CHANNEL_ID
        )
    yield
    if request.config.getoption("--delete"):
        await clear_all()


@pytest_asyncio.fixture(loop_scope="session")
def client():
    yield AsyncClient(app=app, base_url="http://test")


@pytest.fixture(scope="session")
def role_prompt():
    return "你是广东东莞社保助手"
